package com.leetcode;

import com.leetcode.common.TreeNode;
import com.leetcode.util.BinaryTreeUtil;

/**
 * 230. 二叉搜索树中第K小的元素
 * 中序遍历, 递归写法
 *
 * @author fy
 * @date 2022/4/26 20:41
 */
public class Solution230_1 {

    private int res = -1;
    private int k;
    public int kthSmallest(TreeNode root, int k) {
        this.k = k;
        inOrder(root);
        return res;
    }

    private void inOrder(TreeNode node) {
        if (node == null) {
            return;
        }
        if (k <= 0) {
            return;
        }
        inOrder(node.left);
        k -= 1;
        if (k == 0) {
            res = node.val;
        }
        inOrder(node.right);
    }

    public static void main(String[] args) {
        TreeNode root = BinaryTreeUtil.createTree(new Integer[]{3, 1, 4, null, 2});
        int k = 1;
        int res = new Solution230_1().kthSmallest(root, k);
        System.out.println(res);
    }

}
